package com.example.basic;

public class ThreadInternet {
    public static void main(String[] args) {
        Contain contain = new Contain();
        Product product = new Product(contain);
        Consume consume = new Consume(contain);
        new Thread(product,"product").start();
        new Thread(consume,"consume").start();
    }
}
class Product implements Runnable{
    private Contain contain;
    public Product(Contain contain){
        this.contain=contain;
    }
    @Override
    public void run() {
        for (int i = 0; i < 100; i++) {
            Chicken chicken = new Chicken(i);
            contain.pushChicken(chicken);
            System.out.println("放入第"+i+"只鸡");
        }
    }
}
class  Consume implements Runnable{
    private Contain contain;
    public Consume(Contain contain){
        this.contain=contain;
    }
    @Override
    public void run() {
        for (int i = 0; i < 100; i++) {
            Chicken chicken = contain.eatChicken();
            System.out.println("吃掉第"+i+"只鸡");
        }
    }
}
class Chicken{
    private Integer id;
    public Chicken(Integer id){
        this.id=id;
    }
}
class Contain{
   Chicken[] chicken=new Chicken[10];
    private  Integer count=0;
   public synchronized void pushChicken(Chicken children){
           if(count==chicken.length){
               try {
                   this.wait();
               } catch (InterruptedException e) {
                   e.printStackTrace();
               }
           }else {
               chicken[count++]=children;
               this.notifyAll();
           }
       }
   public synchronized Chicken eatChicken(){
       Chicken eatChicken=null;
       if (count!=0){
//           数组下标是9 count是10
           eatChicken= chicken[--count];
           this.notifyAll();
       }else {
           try {
               this.wait();
           } catch (InterruptedException e) {
               e.printStackTrace();
           }
       }
       return eatChicken;
   }
}
